<?php

class Vph{
    //唯品会
    private $AppKey = '';
    private $AppSecret = '';
    private $AccessToken = '';
    private $AppUrl = 'https://gw.vipapis.com/';
    private $Language = 'zh';
    private $service ;

    public function __construct($union)
    {
        $this->AppKey = $union['appKey'];
        $this->AppSecret = $union['appSecret'];
        $this->AccessToken = $union['accessToken'];

        require_once "vips/com/vip/adp/api/open/service/UnionUrlServiceClient.php";
        $this->service=\com\vip\adp\api\open\service\UnionUrlServiceClient::getService();
        $ctx=\Osp\Context\InvocationContextFactory::getInstance();

        $ctx->setAppKey($this->AppKey);
        $ctx->setAppSecret($this->AppSecret);
        $ctx->setAccessToken($this->AccessToken);
        $ctx->setAppURL($this->AppUrl);
        $ctx->setLanguage($this->Language);
    }

    /**
     * 唯品会商品列表
     */
    public function goods_list($params){
        try {
            require_once "vips/com/vip/adp/api/open/service/UnionGoodsServiceClient.php";

            if($params['sort'] == 'desc'){
                $sort = 1;
            } else {
                $sort = 0;
            }
            $service = \com\vip\adp\api\open\service\UnionGoodsServiceClient::getService();
            $ctx = \Osp\Context\InvocationContextFactory::getInstance();
            $ctx->setAppKey($this->AppKey);
            $ctx->setAppSecret($this->AppSecret);
            $ctx->setAccessToken($this->AccessToken);
            $ctx->setAppURL($this->AppUrl);
            $ctx->setLanguage($this->Language);
            $request1=new \com\vip\adp\api\open\service\GoodsInfoRequest();
            $request1->channelType = 0;
            $request1->page = $params['page'];
            $request1->pageSize = $params['page_size'];
            $request1->requestId = $params['user_id'];
            $request1->sourceType = 0;
            if(!in_array($params['category_id'],[1,-1])){
                $request1->sourceType = 1;
                $request1->jxCode = $params['category_id'];
            }
            $request1->fieldName = strtoupper($params['order_by']);
            $request1->order = (int)$sort;
            $data = $service->goodsListWithOauth($request1);
            $responseResult['status'] = true;
            $responseResult['data'] = $this->trun_list($data->goodsInfoList);
            $responseResult['msg'] = "获取成功";
            return $responseResult;
        } catch(\Osp\Exception\OspException $e){
            return ['status'=>false,'msg'=>$e->getMessage(),'data'=>[]];
        }

    }


    /**
     * 商品详情
     * @param $goods_id
     */
    public function goods_detail($goods_id){
        try {
            require_once "vips/com/vip/adp/api/open/service/UnionGoodsServiceClient.php";

            $service = \com\vip\adp\api\open\service\UnionGoodsServiceClient::getService();
            $ctx = \Osp\Context\InvocationContextFactory::getInstance();
            $ctx->setAppKey($this->AppKey);
            $ctx->setAppSecret($this->AppSecret);
            $ctx->setAccessToken($this->AccessToken);
            $ctx->setAppURL($this->AppUrl);
            $ctx->setLanguage($this->Language);
            $goodsIdList1=array();
            $goodsIdList1[0]=$goods_id;
            $data = $service->getByGoodsIdsWithOauth($goodsIdList1,'requestId',0);
            $arr=[
                "GoodsId" => $data[0]->goodsId,
                "Title" => $data[0]->goodsName,
                "ShortTitle" => $data[0]->goodsName,
                "ShopType" => "唯品会",
                "PicLogo" => $data[0]->goodsMainPicture,
                'Suggest'=>'',
                'Couponurl'=> '',
                'CouponStartTime'=>0,//strtotime($res['start_time']) ? $res['start_time'] : 0,
                'CouponEndTime'=>0,//strtotime($res['end_time']) ? $res['end_time'] : 0,
                "CouponMoney"=>0,
                "CouponSurplus"=>0,
                "Price" => $data[0]->marketPrice,
                "EndPrice" => $data[0]->vipPrice,
                "Commission" => $data[0]->commission,
                "MonthSale" => rand(999,10000),
                "Site" => 'vph',
                'SmallImages' => $data[0]->goodsCarouselPictures,
                'PicList'=> $data[0]->goodsDetailPictures,
                'VideoUrl'=>'',
                "ShopName" => $data[0]->brandName,
                "ShopId" => $data[0]->brandStoreSn,
                "ShopUrl"=>'',
                "ShopIcon"=>'',
                "DescTxt"=>sprintf("%.2f",round(4.9,2)),
                "ServTxt"=>sprintf("%.2f",round(4.9,2)),
                "AvgTxt"=>sprintf("%.2f",round(4.9,2)),
            ];
            return ['status'=>true,'msg'=>'获取成功','data'=>$arr];
        } catch(\Osp\Exception\OspException $e){
            return ['status'=>false,'msg'=>$e->getMessage(),'data'=>[]];
        }
    }

    /**
     * 搜索
     * @param $params
     */
    public function goods_search($params){
        $responseReturn = ['status'=>false,'msg'=>'获取失败','data'=>[]];
        try {
            require_once "vips/com/vip/adp/api/open/service/UnionGoodsServiceClient.php";
            if($params['sort'] == 'desc'){
                $order = 1;
            } else {
                $order = 0;
            }
            $service = \com\vip\adp\api\open\service\UnionGoodsServiceClient::getService();
            $ctx = \Osp\Context\InvocationContextFactory::getInstance();
            $ctx->setAppKey($this->AppKey);
            $ctx->setAppSecret($this->AppSecret);
            $ctx->setAccessToken($this->AccessToken);
            $ctx->setAppURL($this->AppUrl);
            $ctx->setLanguage($this->Language);
            $request1=new \com\vip\adp\api\open\service\QueryGoodsRequest();
            $request1->keyword = trim(urldecode($params['keyword']));
            $request1->fieldName = $params['order_by']?strtoupper($params['order_by']):'';
            $request1->order = $order;
            $request1->page = $params['page'];
            $request1->pageSize = $params['page_size'];
            $request1->requestId = "requestId";
            $request1->queryStock=true;
            $request1->queryActivity=true;
            $request1->queryPrepay=true;
            $data = $service->queryWithOauth($request1);
            if(isset($data->goodsInfoList) && $data->goodsInfoList){
                $responseReturn['status'] = true;
                $responseReturn['data'] = $this->trun_list($data->goodsInfoList);
            }
            return $responseReturn;
        } catch(\Osp\Exception\OspException $e){
           return $responseReturn;
        }
    }

    /**
     * https://vop.vip.com/home#/api/method/detail/com.vip.adp.api.open.service.UnionUrlService-1.0.0/genByGoodsIdWithOauth
     * 生成链接
     */
    public function createturn($user_id,$goods_id){
        require_once "vips/com/vip/adp/api/open/service/UnionUrlServiceClient.php";
        try {
            $goodsIdList1=array();
            $goodsIdList1[0]=$goods_id;
            $result = $this->service->genByGoodsIdWithOauth($goodsIdList1,$user_id,$user_id,$user_id,true,true);
            if(!empty($result->urlInfoList)){
                $data['url']=$result->urlInfoList[0]->ulUrl;
                $data['short_url']=$result->urlInfoList[0]->url;
                $data['page_path']=$result->urlInfoList[0]->vipWxUrl;
                $data['wx_code']=$result->urlInfoList[0]->vipWxCode;
                $data['app_url']=$result->urlInfoList[0]->deeplinkUrl;
                $data['long_url']=$result->urlInfoList[0]->longUrl;
                return ['status' => true, 'msg' =>"获取成功",'data'=>$data];
            }else{
                return ['status' => false,'msg'=>'获取失败!'];
            }
        } catch(\Osp\Exception\OspException $e){
            return ['status' => false,'msg'=>'获取失败!'];
        }
    }

    //公共列表转换
    private function trun_list($res,$code=0){
        $data = [];
        $site = "vph";
        foreach($res as $k =>$v){
            $arr=[
                "GoodsId" => $v->goodsId,
                "Title" => $v->goodsName,
                "ShortTitle" => $v->goodsName,
                "ShopType"=> "唯品会",
                "PicLogo" => $v->goodsThumbUrl,
                "Couponurl"=>"",
                "CouponMoney"=>0,
                "CouponSurplus"=>0,
                "Price" => $v->marketPrice,
                "EndPrice" => $v->vipPrice,
                "Commission" => $v->commission,
                "MonthSale" => rand(999,10000),
                "Site" => $site,
                "ShopName" => $v->brandName,
                "ItemFrom"=>'vph',
                "CouponTotal"=>0,
            ];
            $data[]=$arr;
        }
        return $data;
    }


    private function returnOrderDeal($data){
        $responseTurnData=[];
        foreach ($data as $k => $v) {
            foreach ($v->detailList as $k1 => $v1) {
                $order_id     = $v->orderSn . '-' . $v1->goodsId;
                $order_status = $this->get_status($v->orderSubStatusName);
                $order_one = [
                    'orderId' => $order_id,
                    'site' =>'vph',
                    'orderStatus' => $order_status,
                    'orderSrc' => 4,
                    'tag'=>'唯品会',
                    'tagItem'=>'唯品会',
                    'name' => $v1->goodsName,
                    'goodsId' => $v1->goodsId,
                    'images' => $v1->goodsThumb,
                    'rid' => $v->channelTag,
                    'shopName' => "",
                    'price' => $v1->commissionTotalCost,
                    'orderType'=>in_array($order_status,[2,4,6]) ? 1 : 4,
                    'payMoney' =>$v1->commissionTotalCost,
                    'rebateAmount' => $v1->commission,
                    'incomeRate' => $v1->commissionRate,
                    'orderCreateTime' => date('Y-m-d H:i:s', $v->orderTime / 1000),
                    'orderPaidTime' => date('Y-m-d H:i:s', $v->orderTime / 1000),
                    'orderEarningTime' => $v->signTime ? date('Y-m-d H:i:s', $v->signTime / 1000) : null,
                    'settleTime' => $v->settledTime ? date('Y-m-d H:i:s', $v->settledTime / 1000) : null,
                ];
                $responseTurnData[] = $order_one;
            }
        }
        return $responseTurnData;
    }



    /**
     * 拉取订单
     * https://vop.vip.com/home#/api/method/detail/com.vip.adp.api.open.service.UnionOrderService-1.0.0/orderList
     */
    public function getOrder($orderTimeStart, $orderTimeEnd, $page = 1,$size = 20,&$responseMsgDataResult=[])
    {
        require_once "vips/com/vip/adp/api/open/service/UnionOrderServiceClient.php";
        try {
//            $orderTimeStart = strtotime("2021-12-28 09:00:00") * 1000;//strtotime($orderTimeStart) * 1000;
//            $orderTimeEnd = strtotime("2021-12-28 13:00:00") * 1000;//strtotime($orderTimeEnd) * 1000;

//            $orderTimeStart = "2022-07-20 17:30:00";
//            $orderTimeEnd = "2022-07-20 17:40:00";
            $orderTimeStart = strtotime($orderTimeStart) * 1000;
            $orderTimeEnd = strtotime($orderTimeEnd) * 1000;
            $service = \com\vip\adp\api\open\service\UnionOrderServiceClient::getService();
            $ctx     = \Osp\Context\InvocationContextFactory::getInstance();
            $ctx->setAppKey($this->AppKey);
            $ctx->setAppSecret($this->AppSecret);
            $ctx->setAccessToken($this->AccessToken);
            $ctx->setAppURL($this->AppUrl);
            $ctx->setLanguage($this->Language);
            $queryModel1                 = new \com\vip\adp\api\open\service\OrderQueryModel();
            $queryModel1->orderTimeStart = $orderTimeStart;
            $queryModel1->orderTimeEnd   = $orderTimeEnd;
            $queryModel1->page           = $page;
            $queryModel1->pageSize       = $size;
            $queryModel1->requestId      = time().rand(1,999);
            $responseMsg                         = $service->orderListWithOauth($queryModel1);
            $total                       = $page * $size;
            if ($total < $responseMsg->total) {
                $responseMsgDataResult = array_merge($responseMsgDataResult, $responseMsg->orderInfoList);
                if ($responseMsg['hasMore']) {
                    $this->getOrder($orderTimeStart, $orderTimeEnd, $page + 1);
                }
            }else{
                $responseMsgDataResult = $responseMsg->orderInfoList;
            }
            return $this->returnOrderDeal($responseMsgDataResult);
        } catch (\Osp\Exception\OspException $e) {
            var_dump($e->getMessage());
            return [];
        }
    }


    /**
     * 暂时无用
     */
    public function category_list(){
        require_once "vips/vipapis/cup/product/ProductServiceClient.php";
        try {
            $service=\vipapis\cup\product\ProductServiceClient::getService();
            $ctx=\Osp\Context\InvocationContextFactory::getInstance();
            $ctx->setAppKey($this->AppKey);
            $ctx->setAppSecret($this->AppSecret);
//            $ctx->setAppURL("https://gw.vipapis.com/");
            $ctx->setLanguage("zh");
            var_dump($service->getProdCategory(""));
        } catch(\Osp\Exception\OspException $e){
            var_dump($e);
        }
    }

    /**
     * 分类列表
     * @return array
     */
    public function get_categorys(){
        return [
            [
                'name' => '女装精选',
                'category_id' => '7hfpy0m4',
                'site' => 'vph',
                'image'=>'',
            ],
            [
                'name' => '美妆精选',
                'category_id' => 'vd0wbfdx',
                'site' => 'vph',
                'image'=>'',
            ],
            [
                'name' => '数码电子',
                'category_id' => 'dpot8m5u',
                'site' => 'vph',
                'image'=>'',
            ],
            [
                'name' => '精选首饰',
                'category_id' => 'szkl4kj7',
                'site' => 'vph',
                'image'=>'',
            ],
            [
                'name' => '鞋包精选',
                'category_id' => 'byh9331t',
                'site' => 'vph',
                'image'=>'',
            ],
            [
                'name' => '母婴精选',
                'category_id' => 'gkf52p8p',
                'site' => 'vph',
                'image'=>'',
            ],
            [
                'name' => '居家精选',
                'category_id' => 'cnrzcs22',
                'site' => 'vph',
                'image'=>'',
            ],
            [
                'name' => '运动户外精选',
                'category_id' => 'indvf44e',
                'site' => 'vph',
                'image'=>'',
            ],
            [
                'name' => '家用电器',
                'category_id' => 'uggxpyh5',
                'site' => 'vph',
                'image'=>'',
            ],
        ];
    }

    /**
     * 订单状态
     * @param $name
     * @return int
     */
    public function get_status($name){
        $order_status = 0;
        switch ($name){
            case '已下单';
                $order_status = 1;
                break;
            case '已付款';
                $order_status = 2;
                break;
            case '已签收';
                $order_status = 2;
                break;
            case '已失效';
                $order_status = 11;
                break;
            case '待结算';
                $order_status = 2;
                break;
            case '已结算';
                $order_status = 6;
                break;
        }
        return $order_status;
    }


    public function vipLinkCheck($title)
    {
        require_once "vips/com/vip/adp/api/open/service/UnionUrlServiceClient.php";
        $result['status'] = false;
        $result['data'] = [];
        try {
            $service = \com\vip\adp\api\open\service\UnionUrlServiceClient::getService();
            $ctx = \Osp\Context\InvocationContextFactory::getInstance();
            $ctx->setAppKey($this->AppKey);
            $ctx->setAppSecret($this->AppSecret);
            $ctx->setAppURL($this->AppUrl);
            $ctx->setLanguage($this->Language);

            $vipLinkCheckReq1 = new \com\vip\adp\api\open\service\VipLinkCheckReq();
            $vipLinkCheckReq1->source = "source";
            $vipLinkCheckReq1->content = $title;
            $data = $service->vipLinkCheck($vipLinkCheckReq1);

            if(isset($data->successMap) && !empty($data->successMap)){
                $result['status'] = true;
                foreach ($data->successMap as $key=>$val){
                    $result['data'][] = $key;
                }
            }
        } catch (\Osp\Exception\OspException $e) {
        }
        return $result;
    }


    /**
     * https://vop.vip.com/home#/api/method/detail/com.vip.adp.api.open.service.UnionUrlService-1.0.0/genByVIPUrlWithOauth
     * 活动转链
     */
    public function activityTurnlink($chanTag,$url){
        try {
            require_once "vips/com/vip/adp/api/open/service/UnionUrlServiceClient.php";
            $service=\com\vip\adp\api\open\service\UnionUrlServiceClient::getService();
            $ctx=\Osp\Context\InvocationContextFactory::getInstance();
            $ctx->setAppKey($this->AppKey);
            $ctx->setAppSecret($this->AppSecret);
            $ctx->setAccessToken($this->AccessToken);
            $ctx->setAppURL($this->AppUrl);
            $ctx->setLanguage($this->Language);
            $urlList1[0]=$url;

            $urlGenRequest2= new \com\vip\adp\api\open\service\UrlGenRequest();
            $responseMsg = $service->genByVIPUrlWithOauth($urlList1,$chanTag,"requestId","statParam",$urlGenRequest2);
            if(isset($responseMsg->urlInfoList[0])){
                $responseMsgData = $responseMsg->urlInfoList[0];
                $responseMsgResult = [
                    'url' => $responseMsgData->url,
                    'short_url' =>$responseMsgData->source,
                    'page_path' => $responseMsgData->vipWxUrl,
                    'app_url'=>$responseMsgData->deeplinkUrl,
                    'wx_code'=>'',
                ];
                return ['status' => true, 'msg' => "获取成功", 'data' => $responseMsgResult];
            }else{
                return ['status'=>false,'msg'=>'转链失败'];
            }
        } catch(\Osp\Exception\OspException $e){
//            var_dump($e);
            return ['status'=>false,'msg'=>'转链失败'];
        }
    }
}
